package common.mq.basic.service.impl;

import java.util.GregorianCalendar;

import org.springframework.beans.factory.annotation.Autowired;

import common.mq.basic.service.MessageService;
import common.mq.basic.service.QueueManager;
import common.mq.basic.service.QueueService;
import common.mq.po.ExceType;
import common.mq.po.MessType;
import common.mq.po.Message;
import common.mq.po.Queue;
import common.mq.sender.service.ISenderService;

public class QueueServiceImpl implements QueueService {
	
	@Autowired
	private MessageService messageService;
	
	@Autowired
	private QueueManager queueManager;
	
	@Autowired
	private ISenderService iSenderService;

	@Override
	public void receive(Message m, Queue q) throws Exception {
		int now = (int) new GregorianCalendar().getTimeInMillis() / 1000;
		//消息不存在或过期，则抛弃
		if(m == null || m.getOverdueTime() < now ){
			return;
		}
		//队列关闭状态，则停止
		if(q.getStatus() == 2){
			return;
		}
		//克隆一份消息
		Message msg = messageService.cloneMessage(m);
		//如果是时序消息，则需要检查它的时序
		if(msg.getType() == MessType.SEQ && !queueManager.checkSeqRelation(q, msg)){
			//计算下次执行时间
			msg = messageService.updateNextExecute(msg,messageService.gainNextTime(msg));
			//存入等待区域
			queueManager.push(msg, q);
			queueManager.push2Send(msg.getId(),q.getId(),msg.getNextTime() - now);
			return;
		}
		//如果是定时消息，则直接存入等待区域 并异步发送
		if(msg.getType() == MessType.TIMING ){
			//计算下次执行时间
			msg = messageService.updateNextExecute(msg,messageService.gainNextTime(msg));
			//存入等待区域
			queueManager.push(msg, q);
			queueManager.push2Send(msg.getId(),q.getId(),msg.getNextTime() - now);
			return;
		}
		if(!getiSenderService().send(q.getId(), msg)){
			msg.setType(MessType.EXC);
			msg.setExceType(ExceType.DEFAULT);
			//计算下次执行时间
			msg = messageService.updateNextExecute(msg,messageService.gainNextTime(msg));
			//存入等待区域
			queueManager.push(msg, q);
			queueManager.push2Send(msg.getId(),q.getId(),msg.getNextTime() - now);
			return;
		}
		
	}

	public void setQueueManager(QueueManager queueManager) {
		this.queueManager = queueManager;
	}

	public QueueManager getQueueManager() {
		return queueManager;
	}

	public void setMessageService(MessageService messageService) {
		this.messageService = messageService;
	}

	public MessageService getMessageService() {
		return messageService;
	}

	public void setiSenderService(ISenderService iSenderService) {
		this.iSenderService = iSenderService;
	}

	public ISenderService getiSenderService() {
		return iSenderService;
	}

}
